﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;
using System.IO;
using System.Text;
using System.Security.Cryptography;

/// <summary>
/// 提供一些基础方法的支持
/// </summary>
namespace BLL.Common
{
    public class Contexts
    {
        #region Fields


        public const string UserPassportId = "u";

        public const string UserType = "userType";

        public const string PaperId = "pId";

        public const string FamousRegionId = "fRId";

        public const string NewsType = "newsType";

        public const string GoToUrl = "goUrl";

        public const string RegionCategoryId = "rCId";

        public const string ThreadId = "tId";

        public const string UserPostId = "uPId";



        private const string ENCRYPT_KEY = "eMpower!";
        #endregion

        #region Public Properties      
        
        /// <summary>
        /// 获得 http://auto.ipsos.com/www_dalian/fangyuan.asp 的 部分如：http://auto.ipsos.com
        /// </summary>
        public static string HttpPath
        {
            get
            {
                string url = HttpContext.Current.Request.Url.ToString();
                return "http://"+(url.Split('/'))[2].ToString();
            }
        }
        /// <summary>
        /// 得到当前虚拟目录路径
        /// </summary>
        public static string AppPath
        {
            get
            {
                return HttpContext.Current.Request.ApplicationPath.TrimEnd('/');
            }
        }
        /// <summary>
        /// 获取后台虚拟路径
        /// </summary>
        public static string AdminPath
        {
            get
            {
                if (ConfigurationManager.AppSettings["AdminPath"] != null)
                {
                    string path = ConfigurationManager.AppSettings["AdminPath"];
                    
                        path = AppPath + path;

                        return path;
                }
                return AppPath;
            }
        }

        /// <summary>
        /// 获取当前CSS路径
        /// </summary>
        public static string CssPath
        {
            get
            {
                return AppPath + "/Styles";
            }
        }

        /// <summary>
        /// 获取当前Javascript路径
        /// </summary>
        public static string JsPath
        {
            get
            {
                return AppPath + "/Scripts";
            }
        }

        /// <summary>
        /// 获取当前页面路径
        /// </summary>
        public static string ThisPageUrl
        {
            get
            {
                return HttpContext.Current.Request.Path;
            }
        }

        /// <summary>
        /// 获取当前页面路径，且含有页面参数内容
        /// </summary>
        public static string ThisPageUrlWithParams
        {
            get
            {
                return HttpContext.Current.Request.RawUrl;
            }
        }


        public static string GetGoURL()
        {
            return GetValueFromRequest(GoToUrl);
        }

        #endregion

        #region Public Methods

        #region Get parameters

       

      
        /// <summary>
        /// 获取MD5加密字符串
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string GetMD5String(string text)
        {
            byte[] result = Encoding.UTF8.GetBytes(text);
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] output = md5.ComputeHash(result);
            return BitConverter.ToString(output).Replace("-", ""); 
        }
        #endregion

        #region Encrypt and Decrypt

        /// <summary>
        /// 对URL中参数进行加密
        /// </summary>
        /// <param name="param">参数值</param>
        /// <returns>密文</returns>
        public static string GetEncrypt(string param)
        {
            if (string.IsNullOrEmpty(param))
            {
                return string.Empty;
            }
            else
            {
                return EMPower.Utility.SecurityHelper.Encrypt(param, ENCRYPT_KEY);
            }
        }

        /// <summary>
        /// 对URL中的参数解密
        /// </summary>
        /// <param name="param">密文</param>
        /// <returns>参数明文</returns>
        public static string GetDecrypt(string param)
        {
            string result;

            if (string.IsNullOrEmpty(param))
            {
                return string.Empty;
            }
            else
            {
                try
                {
                    result = EMPower.Utility.SecurityHelper.Decrypt(param, ENCRYPT_KEY);
                }
                catch
                {
                    result = string.Empty;
                }
            }

            return result;
        }
        #endregion

        #region 获取参数

        /// <summary>
        /// 获取用户ID
        /// </summary>
        /// <returns></returns>
        public static long GetUserPassportId()
        {
            string paramName = UserPassportId;
            long userPassportId = 0;

            userPassportId = GetLongFromRequest(paramName);

            if (userPassportId < 1)
            {
                string temp = GetValueFromRequest(paramName);
                long result;
                bool isLong = long.TryParse(GetDecrypt(temp), out result);
                if (isLong)
                {
                    userPassportId = result;
                }
            }

            return userPassportId;
        }

        /// <summary>
        /// 获取用户类型
        /// </summary>
        /// <returns></returns>
        public static int GetUserType()
        {
            string paramName = UserType;
            int userType = 0;

            userType = GetIntFromRequest(paramName);

            if (userType < 1)
            {
                string temp = GetValueFromRequest(paramName);
                int result;
                bool isLong = int.TryParse(GetDecrypt(temp), out result);
                if (isLong)
                {
                    userType = result;
                }
            }

            return userType;
        }

        /// <summary>
        /// 获取新闻类型（NewsType）
        /// </summary>
        /// <returns></returns>
        public static int GetNewsType()
        {
            string paramName = NewsType;
            int newsType = 0;

            newsType = GetIntFromRequest(paramName);

            if (newsType < 1)
            {
                string temp = GetValueFromRequest(paramName);
                int result;
                bool isLong = int.TryParse(GetDecrypt(temp), out result);
                if (isLong)
                {
                    newsType = result;
                }
            }

            return newsType;
        }




        /// <summary>
        /// 获取PaperID
        /// </summary>
        /// <returns></returns>
        public static long GetAPPPaperId()
        {
             return GetAPPPaperId(false,string.Empty);
        }

        public static long GetAPPPaperId(string redirectUrl)
        {
            return GetAPPPaperId(true, redirectUrl);
        } 

        /// <summary>
        /// 获取PaperID
        /// </summary>
        /// <param name="isRedirect">是否强行跳转到文章列表</param>
        /// <param name="redirectUrl">跳转到的URL地址</param>
        /// <returns></returns>
        public static long GetAPPPaperId(bool isRedirect, string redirectUrl)
        {
            string paramName = PaperId;
            long paperId = 0;

            paperId = GetLongFromRequest(paramName);

            if (paperId < 1)
            {
                string temp = GetValueFromRequest(paramName);
                long result;
                bool isLong = long.TryParse(GetDecrypt(temp), out result);
                if (isLong)
                {
                    paperId = result;
                }
            }

            if (isRedirect)
            {
                if (paperId < 1)
                {
                    string roleBaseUrl = string.Empty;
                    if (string.IsNullOrEmpty(redirectUrl))
                    {
                        roleBaseUrl = string.Empty;
                    }
                    else
                    {
                        roleBaseUrl = redirectUrl;
                    }

                    if (string.IsNullOrEmpty(roleBaseUrl) || ThisPageUrlWithParams.IndexOf(roleBaseUrl) >= 0)
                    {
                        return 0;
                    }
                    //string redirectUrl = AppPath + roleBaseUrl + "?goToUrl=" + HttpContext.Current.Server.UrlEncode(ThisPageUrlWithParams);
                    HttpContext.Current.Response.Redirect(AppPath +"/"+ roleBaseUrl, true);
                }
            }

            return paperId;
        }

        /// <summary>
        /// 获取RegionCategoryID
        /// </summary>
        /// <returns></returns>
        public static long GetAPPRegionCategoryID()
        {
            return GetAPPRegionCategoryID(false, string.Empty);
        }
        /// <summary>
        /// 获取RegionCategoryID
        /// </summary>
        /// <param name="redirectUrl">跳转到的URL地址</param>
        /// <returns></returns>
        public static long GetAPPRegionCategoryID(string redirectUrl)
        {
            return GetAPPRegionCategoryID(true, redirectUrl);
        }

        /// <summary>
        /// 获取RegionCategoryID
        /// </summary>
        /// <param name="isRedirect">是否强行跳转到文章列表</param>
        /// <param name="redirectUrl">跳转到的URL地址</param>
        /// <returns></returns>
        public static long GetAPPRegionCategoryID(bool isRedirect, string redirectUrl)
        {
            string paramName = RegionCategoryId;
            long paperId = 0;

            paperId = GetLongFromRequest(paramName);

            if (paperId < 1)
            {
                string temp = GetValueFromRequest(paramName);
                long result;
                bool isLong = long.TryParse(GetDecrypt(temp), out result);
                if (isLong)
                {
                    paperId = result;
                }
            }

            if (isRedirect)
            {
                if (paperId < 1)
                {
                    string roleBaseUrl = string.Empty;
                    if (string.IsNullOrEmpty(redirectUrl))
                    {
                        roleBaseUrl = string.Empty;
                    }
                    else
                    {
                        roleBaseUrl = redirectUrl;
                    }

                    if (string.IsNullOrEmpty(roleBaseUrl) || ThisPageUrlWithParams.IndexOf(roleBaseUrl) >= 0)
                    {
                        return 0;
                    }
                    //string redirectUrl = AppPath + roleBaseUrl + "?goToUrl=" + HttpContext.Current.Server.UrlEncode(ThisPageUrlWithParams);
                    HttpContext.Current.Response.Redirect(AppPath + "/" + roleBaseUrl, true);
                }
            }

            return paperId;
        }

        /// <summary>
        /// 获取ThreadId
        /// </summary>
        /// <returns></returns>
        public static long GetAPPThreadId()
        {
            return GetAPPThreadId(false, string.Empty);
        }
        /// <summary>
        /// 获取ThreadId
        /// </summary>
        /// <param name="redirectUrl">跳转到的URL地址</param>
        /// <returns></returns>
        public static long GetAPPThreadId(string redirectUrl)
        {
            return GetAPPThreadId(true, redirectUrl);
        }

        /// <summary>
        /// 获取ThreadId
        /// </summary>
        /// <param name="isRedirect">是否强行跳转到文章列表</param>
        /// <param name="redirectUrl">跳转到的URL地址</param>
        /// <returns></returns>
        public static long GetAPPThreadId(bool isRedirect, string redirectUrl)
        {
            string paramName = ThreadId;
            long paperId = 0;

            paperId = GetLongFromRequest(paramName);

            if (paperId < 1)
            {
                string temp = GetValueFromRequest(paramName);
                long result;
                bool isLong = long.TryParse(GetDecrypt(temp), out result);
                if (isLong)
                {
                    paperId = result;
                }
            }

            if (isRedirect)
            {
                if (paperId < 1)
                {
                    string roleBaseUrl = string.Empty;
                    if (string.IsNullOrEmpty(redirectUrl))
                    {
                        roleBaseUrl = string.Empty;
                    }
                    else
                    {
                        roleBaseUrl = redirectUrl;
                    }

                    if (string.IsNullOrEmpty(roleBaseUrl) || ThisPageUrlWithParams.IndexOf(roleBaseUrl) >= 0)
                    {
                        return 0;
                    }
                    //string redirectUrl = AppPath + roleBaseUrl + "?goToUrl=" + HttpContext.Current.Server.UrlEncode(ThisPageUrlWithParams);
                    HttpContext.Current.Response.Redirect(AppPath + "/" + roleBaseUrl, true);
                }
            }

            return paperId;
        }

        /// <summary>
        /// 获取UserPostId
        /// </summary>
        /// <returns></returns>
        public static long GetAPPUserPostId()
        {
            return GetAPPUserPostId(false, string.Empty);
        }
        /// <summary>
        /// 获取ThreadId
        /// </summary>
        /// <param name="redirectUrl">跳转到的URL地址</param>
        /// <returns></returns>
        public static long GetAPPUserPostId(string redirectUrl)
        {
            return GetAPPUserPostId(true, redirectUrl);
        }

        /// <summary>
        /// 获取ThreadId
        /// </summary>
        /// <param name="isRedirect">是否强行跳转到文章列表</param>
        /// <param name="redirectUrl">跳转到的URL地址</param>
        /// <returns></returns>
        public static long GetAPPUserPostId(bool isRedirect, string redirectUrl)
        {
            string paramName = UserPostId;
            long paperId = 0;

            paperId = GetLongFromRequest(paramName);

            if (paperId < 1)
            {
                string temp = GetValueFromRequest(paramName);
                long result;
                bool isLong = long.TryParse(GetDecrypt(temp), out result);
                if (isLong)
                {
                    paperId = result;
                }
            }

            if (isRedirect)
            {
                if (paperId < 1)
                {
                    string roleBaseUrl = string.Empty;
                    if (string.IsNullOrEmpty(redirectUrl))
                    {
                        roleBaseUrl = string.Empty;
                    }
                    else
                    {
                        roleBaseUrl = redirectUrl;
                    }

                    if (string.IsNullOrEmpty(roleBaseUrl) || ThisPageUrlWithParams.IndexOf(roleBaseUrl) >= 0)
                    {
                        return 0;
                    }
                    //string redirectUrl = AppPath + roleBaseUrl + "?goToUrl=" + HttpContext.Current.Server.UrlEncode(ThisPageUrlWithParams);
                    HttpContext.Current.Response.Redirect(AppPath + "/" + roleBaseUrl, true);
                }
            }

            return paperId;
        }
        #endregion

        #region Basic safe request methods

        /// <summary>
        /// 构造函数
        /// </summary>
        public Contexts()
        {

        }

        /// <summary>
        /// 替换编辑框里边的class和href内容
        /// </summary>
        /// <param name="boday">编辑框的内容</param>
        /// <returns></returns>
        public static string ReplaceClassAndHref(string boday)
        {
            string okstr = string.Empty;

            if (!string.IsNullOrEmpty(boday))
            {
                Regex classReg = new Regex("class\\s?=\\s?\".+?\"");
                //Regex styleReg = new Regex("style\\s?=\\s?\".+?\"");
                //Regex hrefReg = new Regex("href\\s?=\\s?\".+?\"");
                //Regex idReg = new Regex("id\\s?=\\s?\".+?\"");
                //Regex divReg = new Regex("div");
                boday = classReg.Replace(boday, "");
                //boday = styleReg.Replace(boday, "");
                //boday = hrefReg.Replace(boday, "");
                //boday = idReg.Replace(boday, "");
                //boday = divReg.Replace(boday, "span");
                okstr = boday;
            }
            return okstr;
        }

        /// <summary>
        /// 自动关闭标签
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string CloseHTML(string str)
        {
            string[] HtmlTag = new string[] { "p", "div", "span", "table", "ul", "font", "b", "u", "i", "a", "h1", "h2", "h3", "h4", "h5", "h6" };

            for (int i = 0; i < HtmlTag.Length; i++)
            {
                int OpenNum = 0, CloseNum = 0;
                Regex re = new Regex("<" + HtmlTag + "[^>]*" + ">", RegexOptions.IgnoreCase);
                MatchCollection m = re.Matches(str);
                OpenNum = m.Count;
                re = new Regex("</" + HtmlTag + ">", RegexOptions.IgnoreCase);
                m = re.Matches(str);
                CloseNum = m.Count;

                for (int j = 0; j < OpenNum - CloseNum; j++)
                {
                    str += "</" + HtmlTag + ">";
                }
            }

            return str;
        }

        /// <summary>
        /// 获取页面参数值
        /// </summary>
        /// <param name="param">参数名</param>
        /// <returns></returns>
        public static string GetValueFromRequest(string param)
        {
            string requestValue = HttpContext.Current.Request[param];
            if (string.IsNullOrEmpty(requestValue))
            {
                requestValue = string.Empty;
            }

            return requestValue;
        }

        /// <summary>
        /// 获取页面整型参数值
        /// </summary>
        /// <param name="param">参数名</param>
        /// <returns></returns>
        public static int GetIntFromRequest(string param)
        {
            int returnValue = 0;
            string queryStringValue = GetValueFromRequest(param);
            if (string.IsNullOrEmpty(queryStringValue))
            {
                return returnValue;
            }
            try
            {
                if (!int.TryParse(queryStringValue, out returnValue))
                {
                    returnValue = int.Parse(GetDecrypt(queryStringValue));
                }
                //if (Convert.ToInt32(queryStringValue) < returnValue)
                //    return returnValue;
            }
            catch
            {
                return returnValue;
            }

            return returnValue;
        }

        /// <summary>
        /// 获取页面整型参数值
        /// </summary>
        /// <param name="param">参数名</param>
        /// <returns></returns>
        public static long GetLongFromRequest(string param)
        {
            long returnValue = 0;
            string queryStringValue = GetValueFromRequest(param);
            if (string.IsNullOrEmpty(queryStringValue))
            {
                return returnValue;
            }
            try
            {
                if (!long.TryParse(queryStringValue, out returnValue))
                {
                    returnValue = long.Parse(GetDecrypt(queryStringValue));
                }
                //if (Convert.ToInt64(queryStringValue) < returnValue)
                //    return returnValue;
            }
            catch
            {
                return returnValue;
            }

            return returnValue;
        }

        /// <summary>
        /// 获取页面字符型参数值
        /// </summary>
        /// <param name="param">参数名</param>
        /// <returns></returns>
        public static string GetStringFromRequest(string param)
        {
            string returnValue = "";
            string queryStringValue = GetValueFromRequest(param);
            if (string.IsNullOrEmpty(queryStringValue))
                return returnValue;
            return queryStringValue;
        }

        /// <summary>
        /// 输入字符格式化 目前最笨的方法 ---- 需要优化
        /// </summary>
        /// <param name="str">参数</param>
        /// <returns></returns>
        public static string GetContextReplace(string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                return str.Replace("class=", "ipsos=");
            }
            return null;
        }

        /// <summary>
        /// 删除指定的文件
        /// </summary>
        /// <param name="path">文件的绝对路径</param>
        public static void DeleteFile(string path)
        {
            if (!string.IsNullOrEmpty(path))
            {
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
            }
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="filePath"></param>
        public static void DownLoad(Page p, string filePath)
        {
            System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);

            if (fileInfo.Exists == true)
            {
                const long ChunkSize = 102400;//100K 每次读取文件，只读取100K，这样可以缓解服务器的压力 
                byte[] buffer = new byte[ChunkSize];

                p.Response.Clear();
                System.IO.FileStream iStream = System.IO.File.OpenRead(filePath);
                long dataLengthToRead = iStream.Length;//获取下载的文件总大小 
                p.Response.ContentType = "application/octet-stream";
                p.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileInfo.Name));
                while (dataLengthToRead > 0 && p.Response.IsClientConnected)
                {
                    int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));//读取的大小 
                    p.Response.OutputStream.Write(buffer, 0, lengthRead);
                    p.Response.Flush();
                    dataLengthToRead = dataLengthToRead - lengthRead;
                }
                p.Response.Close();
                iStream.Flush();
                iStream.Close();
            }
        }

        #endregion

        #endregion
    }
}